package groupon.common.dao.impl;

import groupon.common.dao.GenericDao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;

import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.stereotype.Repository;

@Repository(value = "genericDao")
public class GenericDaoImpl<T extends Serializable, ID extends Serializable> implements GenericDao<T, ID> {

	
	private EntityManager _entityManager;
	
	private JpaTemplate _jpaTemplate;

	public EntityManager getEntityManager() {
		return _entityManager;
	}
	
	@PersistenceContext(unitName = "entityManagerFactory")
	public void setEntityManager(EntityManager entityManager) {
		_entityManager = entityManager;
		_jpaTemplate = new JpaTemplate(_entityManager);
	}

	public final void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
		System.out.println(">>>>>>sjsjsjsjs");
        _jpaTemplate = new JpaTemplate(entityManagerFactory);
        _entityManager = entityManagerFactory.createEntityManager();
    }


	public GenericDaoImpl(){
	}
	
	public long count(Class<T> cls) {
		return (Long)_entityManager.createQuery("select count(t) from " + cls.getSimpleName() + " t").getSingleResult();
	}

	public void delete(T entity) {
		_entityManager.remove(entity);
		
	}

	public T find(Class<T> cls, ID id) {
		return _entityManager.find(cls, id);
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll(Class<T> cls) {
		return _entityManager.createQuery("select t from " + cls.getSimpleName() + " t").getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<T> findInRange(Class<T> cls, int firstResult, int maxResults) {
		return _entityManager.createQuery("select t from " + cls.getSimpleName() + " t").setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
	}

	public T merge(T entity) {
		return _entityManager.merge(entity);
	}

	public void persist(T entity) {
		_entityManager.persist(entity);
	}

	public JpaTemplate getJpaTemplate() {
		return _jpaTemplate;
	}

	public void setJpaTemplate(JpaTemplate jpaTemplate) {
		_jpaTemplate = jpaTemplate;
	}
	
	public CriteriaBuilder criteriaBuilder() {
		return _entityManager.getCriteriaBuilder();
	}
	
}
